<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名字" width="120">
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="100">
      </el-table-column>
      <el-table-column prop="update_time" label="修改时间" width="100">
      </el-table-column>
      <el-table-column prop="emp.username" label="部门经理" width="80">
      </el-table-column>
      <el-table-column prop="dept.name" label="父部门" min-width="80">
      </el-table-column>
      <el-table-column prop="path" label="部门路径" width="120">
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="50">
        <template scope="scope">
          <span v-if="scope.row.state == 0" style="color: red;">禁用</span>
          <span v-if="scope.row.state == 1" style="color: mediumspringgreen">启用</span>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="描述" width="180">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--      <el-pagination-->
<!--          layout="total, prev, pager, next"-->
<!--          @current-change="handleCurrentChange"-->
<!--          :page-size="10"-->
<!--          :total="pageInfo.total"-->
<!--          style="float:right;">-->
<!--      </el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total" style="float:right;">
      </el-pagination>
    </el-col>


		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="管理员">
          <el-select v-model="addForm.emp" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="addForm.dept"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
<!--        <el-form-item label="父部门">-->
<!--          <el-input v-model="addForm.dept.id" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="状态">
            <el-radio-group v-model="addForm.state">
                <el-radio class="radio" :label="1">启动</el-radio>
              <el-radio class="radio" :label="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input type="textarea" v-model="addForm.intro"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
        employees:[],
        deptTree:[],
        // emp:[],
        // dep:[],

				filters: {
					name: ''
				},
        pageInfo:{
          total:0,
          rows:[]
        },
        query:{
          currentPage:1,
          pageSize:10,
          keyword:""
        },
				users: [],
				listLoading: false,
				sels: [],//列表选中列


				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
          id:null,
          name: '',
          intro:"",
          emp:{
            id:null,
            username:""
          },
          dept:{
            id:null,
            name:""
          },
          state:null,

        }

			}
		},
		methods: {

		  getDeptTree(){
        this.$http.get("/dept/tree")
            .then(res =>{
              res=res.data;
              console.log(res.data)
              if (res.success){
                this.deptTree=res.data;
              }
            })
            .catch(res =>{


            })
      },

		  getAllEmployee(){
		    this.$http.get("/emp")
          .then(res =>{
                res=res.data;
            console.log(res.data)
                if (res.success){
                    this.employees=res.data;
                }
          })
          .catch(res =>{


          })
      },

      //状态的显示转换
      formatState: function (row, column) {
        return row.state == 0 ? '正常' : '停用 ';
      },

		  search(){
        this.query.currentPage = 1;
        this.getDepartment();
      },

      handleCurrentChange(val) {
        this.query.currentPage = val;
        this.getDepartment();
      },

      handleSizeChange(val){
        this.query.pageSize=val;
        this.getDepartment();
      },

      getDepartment(){
        this.$http.post("/dept",this.query)
            .then(result => {
              console.log("部门分页查询---")
              console.log(result);
              result = result.data;
              this.pageInfo = result.data;
            }).catch(result => {
          this.$message({ message: '分页查询失败',type: 'error'});
        })
      },

			//删除  index:当前数据的行号    row:当前行数据
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?','提示',{
					type: 'warning'
				}).then(() => {
					this.listLoading = true;  //加载框 true-加载

          let id=row.id;
          this.$http.delete("/dept/"+id).then(res =>{
            this.listLoading=false;
            res=res.data;
            if(res.success){
              this.$message({message: '删除成功', type: 'success'});
            }else {
              this.$message({message:res.message, type: 'error'});
            }
            this.query.currentPage=1
            this.getDepartment();
          })

				}).catch(() => {
              this.$message('删除操作已取消')
				});
			},
			//显示编辑界面
      handleEdit: function (index,row) {
        this.addFormVisible = true;
        //将当前对象赋值给addform  回显
        this.addForm=Object.assign({},row);
        this.getAllEmployee();
        this.getDeptTree()
        if(!row.dept){
              this.addForm.dept={
                id:null,
                name:""
              };
        }
        if(!row.emp){
           this.addForm.emp={
             id:null,
             name:""
           }
        }
        // 联级下拉框 数据回显 需要处理dept.id
        var split=row.path.split("/");
        var temp=[];
        for (var i=1;i<split.length-1;i++){
          temp.push(parseInt(split[i]));
        }
        this.addForm.dept=temp;
        console.log("------------------")
        console.log(temp)

      },
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.getAllEmployee();
				this.getDeptTree();
				this.addForm = {
				  id:null,
					name: '',
          intro:"",
          emp:{
            id:null,
            username:""
          },
          dept:{
            id:null,
            name:""
          },
          state:null
				};
			},

			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
              this.$confirm('确定提交？','提示',{}).then(() =>{
                 this.addLoading=true;
                 let para = Object.assign({},this.addForm);
                console.log("==================")
                 console.log(para)
                 // 前端处理 path方法
                 var array=para.dept;
                 if(array && array.length > 0){
                      para.dept={id:array[array.length-1]};
                 }else {
                    para.dept={id:null};
                 }

                // console.log("-----------------")
                // console.log(this.addForm);
                //   if(this.addForm.dept.length==0){
                //     this.addForm.dept={
                //       id:null,
                //       name:"",
                //     }
                //   }
                  this.$http.put("/dept",para).then(res =>{
                     res=res.data;
                     this.addLoading=false;
                     if(res.success){
                       this.$message({message: '保存成功', type: 'success'});
                       this.query.currentPage=1;
                       this.getDepartment();
                       this.addFormVisible=false;
                     }else {
                       this.$message({message: res.message, type: 'error'});
                     }
                  }).catch(res =>{
                    this.$message({message: '网络错误', type: 'error'});
                  })
              })
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
        console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/dept",ids).then(res =>{
					  res= res.data;
					  if(res.success){
              this.$message({message: '删除成功', type: 'success'});
              this.listLoading=false;
              this.query.currentPage=1;
              this.getDepartment();
					  }else {
              this.$message({message: res.message, type: 'error'});
            }
          })


				}).catch(() => {
          this.$message({message: '取消删除', type: 'error'});
				});
			}
		},


		mounted() {
      this.getDepartment();
		}
	}

</script>

<style scoped>

</style>